/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.sys.modular.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.exception.enums.StatusExceptionEnum;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.sys.core.enums.AdminTypeEnum;
import vip.xiaonuo.sys.modular.project.dto.ProjectQryDto;
import vip.xiaonuo.sys.modular.project.entity.Project;
import vip.xiaonuo.sys.modular.project.enums.ProjectExceptionEnum;
import vip.xiaonuo.sys.modular.project.mapper.ProjectMapper;
import vip.xiaonuo.sys.modular.project.param.ProjectParam;
import vip.xiaonuo.sys.modular.project.service.ProjectService;
import vip.xiaonuo.sys.modular.project.vo.ProjectVo;

import java.util.Date;
import java.util.List;

/**
 * 实验项目service接口实现类
 *
 * @author 8
 * @date 2022-07-06 16:30:03
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Override
    public PageResult<ProjectVo> getPageList(ProjectQryDto dto) {
        //当前登录用户
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (!sysLoginUser.getAdminType().equals(AdminTypeEnum.SUPER_ADMIN.getCode())) {
            dto.setCollId(sysLoginUser.getCollId());
        }
        return new PageResult<>(this.baseMapper.getPageList(PageFactory.defaultPage(dto), dto));
    }

    @Override
    public List<ProjectVo> getList(ProjectQryDto dto) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (!sysLoginUser.getAdminType().equals(AdminTypeEnum.SUPER_ADMIN.getCode())) {
            dto.setCollId(sysLoginUser.getCollId());
        }
        return this.baseMapper.getList(dto);
    }

    @Override
    public void add(ProjectParam projectParam) {
        if (getInfoByParam(projectParam.getName(), projectParam.getCollId(), null) != null) {
            throw new ServiceException(ProjectExceptionEnum.REPEAT_NAME);
        }
        Project project = new Project();
        BeanUtil.copyProperties(projectParam, project);
        this.save(project);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ProjectParam> projectParamList) {
        projectParamList.forEach(projectParam -> {
            this.delById(projectParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ProjectParam projectParam) {
        if (getInfoByParam(projectParam.getName(), projectParam.getCollId(), projectParam.getId()) != null) {
            throw new ServiceException(ProjectExceptionEnum.REPEAT_NAME);
        }
        Project project = this.queryProject(projectParam);
        BeanUtil.copyProperties(projectParam, project);
        this.updateById(project);
    }

    @Override
    public Project detail(ProjectParam projectParam) {
        return this.queryProject(projectParam);
    }

    @Override
    public void changeStatus(ProjectParam projectParam) {
        //当前登录用户
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        Long id = projectParam.getId();

        Integer status = projectParam.getStatus();
        //校验状态在不在枚举值里
        CommonStatusEnum.validateStatus(status);
        //更新枚举，更新只能更新未删除状态的
        LambdaUpdateWrapper<Project> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Project::getId, id)
                .and(i -> i.ne(Project::getStatus, CommonStatusEnum.DELETED.getCode()))
                .set(Project::getStatus, status).set(Project::getUpdateTime, new Date()).set(Project::getUpdateUser, sysLoginUser.getId());
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new ServiceException(StatusExceptionEnum.UPDATE_STATUS_ERROR);
        }

    }

    /**
     * 获取实验项目
     *
     * @author 8
     * @date 2022-07-06 16:30:03
     */
    private Project queryProject(ProjectParam projectParam) {
        Project project = this.getById(projectParam.getId());
        if (ObjectUtil.isNull(project)) {
            throw new ServiceException(ProjectExceptionEnum.NOT_EXIST);
        }
        return project;
    }

    private int delById(Long id) {
        //当前登录用户
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        Project entity = new Project();
        entity.setId(id);
        entity.setStatus(2);
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(sysLoginUser.getId());
        return this.updateById(entity) ? 1 : 0;
    }

    private Project getInfoByName(String name) {
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Project::getStatus, 0, 1);
        queryWrapper.lambda().eq(Project::getName, name);
        return this.getOne(queryWrapper);
    }

    private Project getInfoByParam(String name, Long collId, Long id) {
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Project::getStatus, 0, 1);
        queryWrapper.lambda().eq(Project::getName, name);
        queryWrapper.lambda().eq(Project::getCollId, collId);
        if (id != null) {
            queryWrapper.lambda().ne(Project::getId, id);
        }
        return this.getOne(queryWrapper);
    }

}
